package validator

import (
	"reflect"
	"strconv"
	"strings"
)

func NewNumberValidator[T RangeTypes](tagItem string) Validator {
	if len(tagItem) <= 2 {
		return nil
	}
	var fch, lch = tagItem[0], tagItem[len(tagItem)-1]
	content := tagItem[1 : len(tagItem)-1]
	items := strings.Split(content, ":")
	if len(items) == 2 {
		// 有范围标志
		var min *Border[int]
		if items[0] != "" {
			// 有最小值
			val, err := strconv.ParseInt(items[0], 10, 64)
			if err != nil {
				return nil
			}
			min = &Border[int]{Value: int(val), Include: fch == '['}
		}
		var max *Border[int]
		if items[1] != "" {
			// 有最大值
			val, err := strconv.ParseInt(items[1], 10, 64)
			if err != nil {
				return nil
			}
			max = &Border[int]{Value: int(val), Include: lch == ']'}
		}
		return NewRangeValidator(min, max, func(v reflect.Value) int {
			return int(v.Int())
		})
	}
	items = strings.Split(content, ",")
	var nums []T
	for _, item := range items {
		v, err := strconv.ParseInt(item, 10, 64)
		if err == nil {
			nums = append(nums, T(v))
		}
	}
	if fch == '(' {
		// not in
		return NewNotInValidator(nums, func(v reflect.Value) T {
			return T(v.Int())
		})
	}
	return NewInValidator(nums, func(v reflect.Value) T {
		return T(v.Int())
	})
}
